<template>
  <div class="city-setting-container">
    <!-- Header Toolbar -->
    <div class="city-header">
      <h1>城市设置</h1>
      
      <!-- Search Bar -->
      <div class="search-container">
        <input 
          v-model="searchQuery" 
          type="text" 
          class="search-input" 
          placeholder="搜索城市名称..."
          @input="handleSearch"
        />
      </div>
      
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '加载中...' : '刷新' }}
        </button>
        <button class="add-btn" @click="openAddDialog">
          添加
        </button>
      </div>
    </div>
    
    <!-- Content Area -->
    <div class="city-content" @scroll="handleScroll">
      
      <!-- Loading State -->
      <div v-if="loading && cities.length === 0" class="loading-state">
        <div class="loading-spinner large"></div>
        <p>加载中...</p>
      </div>
      
      <!-- Error State -->
      <div v-else-if="error" class="error-state">
        <div class="error-icon">⚠️</div>
        <h3>加载失败</h3>
        <p>{{ error }}</p>
        <button @click="refreshData" class="retry-btn">重试</button>
      </div>
      
      <!-- Empty State -->
      <div v-else-if="cities.length === 0" class="empty-state">
        <div class="empty-icon">🌆</div>
        <h3>暂无城市数据</h3>
        <p>点击上方“添加”按钮创建第一个城市</p>
      </div>
      
      <!-- Cities List -->
      <div v-else class="city-list">
        <div 
          v-for="city in cities" 
          :key="city.cityCode"
          class="city-item"
        >
          <!-- City Info -->
          <div class="city-info">
            <div class="city-main">
              <div class="city-name-row">
                <h3 class="city-name">{{ city.city }}</h3>
                <span class="city-code">城市代码: {{ city.cityCode }}</span>
              </div>
            </div>
          </div>
          
          <!-- Operations -->
          <div class="city-operations">
            <button 
              class="op-btn update-btn" 
              @click="handleUpdate(city)"
              title="编辑"
            >
              编辑
            </button>
            <button 
              class="op-btn delete-btn" 
              @click="handleDelete(city)"
              title="删除"
            >
              删除
            </button>
          </div>
        </div>
        
        <!-- Loading More State -->
        <div v-if="loading && cities.length > 0" class="loading-more">
          <div class="loading-spinner"></div>
          <p>加载更多...</p>
        </div>
        
        <!-- No More Data State -->
        <div v-if="!loading && cities.length > 0 && hasLoadedAll" class="no-more-data">
          <p>已加载全部数据</p>
        </div>
      </div>
    </div>
    
    <!-- City Footer -->
    <div class="city-footer">
      <div class="footer-content">
        <p class="footer-text">城市数据管理 - 配置城市数据</p>
      </div>
    </div>
    
    <!-- Add City Modal -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeAddModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>添加城市</h2>
          <button class="close-btn" @click="closeAddModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitAddForm" class="city-form">
            <div class="form-group">
              <label>城市名称 *</label>
              <input 
                v-model="addForm.city" 
                type="text" 
                class="form-input" 
                placeholder="请输入城市名称"
                required
              />
            </div>
            <div class="form-group">
              <label>城市代码 *</label>
              <input 
                v-model="addForm.cityCode" 
                type="text" 
                class="form-input" 
                placeholder="请输入城市代码"
                required
              />
            </div>
            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeAddModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="addLoading">
                <span v-if="addLoading" class="loading-spinner"></span>
                {{ addLoading ? '添加中...' : '添加' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core'

// 定义城市数据类型
interface City {
  cityCode: string;
  city: string;
}

// 定义API响应类型
interface ApiResponse {
  code: number; // 200表示成功
  status: number; // 1表示成功
  msg: string;
  data: {
    records: City[];
    total: number;
    size: number;
    current: number;
    pages: number;
    searchCount: boolean;
    optimizeCountSql: boolean;
    orders: any[];
  };
}

// 定义刷新城市API响应类型
interface RefreshCitiesResponse {
  code: number;
  status: boolean;
  msg: string;
  data: boolean;
}

// 定义添加城市表单数据类型
interface AddCityForm {
  city: string;
  cityCode:string
}

// 状态管理
const cities = ref<City[]>([]);
const loading = ref(false);
const error = ref('');
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);
const searchQuery = ref('');
const hasLoadedAll = ref(false); // 是否已加载全部数据
const contentRef = ref<HTMLDivElement>(null); // 内容区域引用

// 添加城市表单状态
const showAddModal = ref(false);
const addLoading = ref(false);
const addForm = ref<AddCityForm>({
  city: ''
});

// 获取城市列表
const fetchCities = async (pageNum: number, query: string = '', append: boolean = false) => {
  // 如果已经加载全部数据，则不再请求
  if (hasLoadedAll.value && append) {
    return;
  }
  
  loading.value = true;
  error.value = '';
  
  try {
    // 调用Tauri命令获取城市数据
    const response = await invoke<ApiResponse>('search_cities', {
      pageNum,
      pageSize: pageSize.value,
      city: query
    });
    
    // 检查请求是否成功
    const success = response.status === 1 && response.code === 200;
    
    if (success && response.data && Array.isArray(response.data.records)) {
      // 从API响应中获取城市数据
      const cityRecords = response.data.records;
      
      // 从API获取的分页信息
      total.value = response.data.total;
      currentPage.value = pageNum;
      
      // 判断是否加载全部数据
      hasLoadedAll.value = append && cities.value.length + cityRecords.length >= total.value;
      
      // 根据是否追加数据决定如何更新城市列表
      if (append) {
        // 追加数据，避免重复
        const existingCodes = new Set(cities.value.map(city => city.cityCode));
        const newCities = cityRecords.filter(city => !existingCodes.has(city.cityCode));
        cities.value = [...cities.value, ...newCities];
      } else {
        // 替换数据
        cities.value = cityRecords;
        // 重置已加载全部数据的状态
        hasLoadedAll.value = cityRecords.length >= total.value;
      }
    } else {
      error.value = response.msg || '获取城市数据失败';
    }
  } catch (err) {
    error.value = `获取城市数据失败：${err instanceof Error ? err.message : '未知错误'}`;
  } finally {
    loading.value = false;
  }
};

// 处理滚动事件
const handleScroll = (event: Event) => {
  const target = event.target as HTMLDivElement;
  
  // 当滚动到底部附近且不在加载中且未加载全部数据时，加载更多
  if (
    target.scrollTop + target.clientHeight >= target.scrollHeight - 100 && 
    !loading.value && 
    !hasLoadedAll.value && 
    cities.length > 0 && 
    !error.value
  ) {
    fetchCities(currentPage.value + 1, searchQuery.value, true);
  }
};

// 刷新数据
const refreshData = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 首先调用刷新城市API
    const refreshResponse = await invoke<RefreshCitiesResponse>('refresh_cities');
    
    // 检查刷新请求是否成功
    if (refreshResponse.status && refreshResponse.code === 200) {
      // 刷新成功后，重新加载数据
      currentPage.value = 1;
      hasLoadedAll.value = false;
      fetchCities(currentPage.value, searchQuery.value);
    } else {
      // 刷新失败，显示错误消息
      error.value = refreshResponse.msg || '刷新城市数据失败';
      loading.value = false;
    }
  } catch (err) {
    error.value = '调用刷新接口失败';
    loading.value = false;
    console.error('Refresh cities API error:', err);
  }
};

// 处理搜索
const handleSearch = () => {
  // 搜索时重置为第一页，并清空现有数据
  currentPage.value = 1;
  hasLoadedAll.value = false;
  fetchCities(currentPage.value, searchQuery.value);
};

// 打开添加对话框
const openAddDialog = () => {
  addForm.value = {
    city: ''
  };
  showAddModal.value = true;
};

// 关闭添加对话框
const closeAddModal = () => {
  showAddModal.value = false;
};

// 提交添加表单
const submitAddForm = async () => {
  if (!addForm.value.city.trim()) {
    // 显示错误提示
    if (window.showToast) {
      window.showToast?.('请输入城市名称', 'error', 2000);
    }
    return;
  }
  
  addLoading.value = true;
  
  try {
    // 根据API规范，调用添加城市的API
    const response = await invoke<any>('add_city', {
      cityCode: addForm.value.cityCode.trim(),
      city: addForm.value.city.trim()
    });
    
    // 处理响应
    const success = response.status === true || response.code === 200;
    
    if (success && response.data === 1) {
      // 显示成功提示
      if (window.showToast) {
        window.showToast?.('城市添加成功', 'success', 2000);
      }
      
      // 关闭对话框并刷新数据
      closeAddModal();
      refreshData();
    } else {
      // 显示错误提示
      if (window.showToast) {
        window.showToast?.(`添加城市失败：${response.msg || '未知错误'}`, 'error', 2000);
      }
    }
  } catch (err) {
    // 显示错误提示
    if (window.showToast) {
      window.showToast?.(`添加城市失败：${err instanceof Error ? err.message : '未知错误'}`, 'error', 2000);
    }
  } finally {
    addLoading.value = false;
  }
};

// 处理更新城市
const handleUpdate = (city: City) => {
  // 实现编辑功能（目前仅UI）
  if (window.showToast) {
    window.showToast?.('编辑功能正在开发中...', 'info', 2000);
  }
};

// 处理删除城市
const handleDelete = (city: City) => {
  // 实现删除功能（目前仅UI）
  if (window.showToast) {
    window.showToast?.('删除功能正在开发中...', 'info', 2000);
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCities(currentPage.value);
});
</script>

<style scoped>
/* Container Styles */
.city-setting-container {
  background-color: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

/* Header Styles */
.city-header {
  display: flex;
  align-items: center;
  gap: 20px;
  background-color: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
  padding: 16px 20px;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.city-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.refresh-btn, .add-btn {
  padding: 10px 20px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn {
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.refresh-btn:hover:not(:disabled) {
  background-color: var(--bg-tertiary);
  border-color: var(--border-hover);
}

.add-btn {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border-color: var(--accent-primary);
}

.add-btn:hover {
  background-color: var(--accent-primary-hover);
  border-color: var(--accent-primary-hover);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Search Bar Styles */
.search-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-input {
  width: 100%;
  max-width: 400px;
  padding: 10px 16px;
  background-color: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 6px;
  color: var(--text-primary);
  font-size: 14px;
  transition: all 0.3s ease;
}



.search-input:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}

.search-input::placeholder {
  color: var(--text-muted);
}

/* Content Area Styles */
.city-content {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
}

/* Loading State */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  gap: 16px;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid var(--border);
  border-top: 2px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-spinner.large {
  width: 40px;
  height: 40px;
  border-width: 3px;
  border-top-width: 3px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Error State */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  gap: 16px;
  text-align: center;
  padding: 0 20px;
}

.error-icon {
  font-size: 48px;
}

.error-state h3 {
  margin: 0;
  font-size: 20px;
  color: var(--text-primary);
}

.error-state p {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
  max-width: 400px;
}

.retry-btn {
  padding: 10px 20px;
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background-color: var(--accent-primary-hover);
}

/* Empty State */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  gap: 16px;
  text-align: center;
  padding: 0 20px;
}

/* Loading More State */
.loading-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  gap: 8px;
}

.loading-more .loading-spinner {
  width: 24px;
  height: 24px;
}

.loading-more p {
  margin: 0;
  font-size: 14px;
  color: var(--text-secondary);
}

/* No More Data State */
.no-more-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  margin-top: 10px;
  border-top: 1px solid var(--border);
}

.no-more-data p {
  margin: 0;
  font-size: 14px;
  color: var(--text-muted);
}

.empty-icon {
  font-size: 48px;
}

.empty-state h3 {
  margin: 0;
  font-size: 20px;
  color: var(--text-primary);
}

.empty-state p {
  margin: 0;
  color: var(--text-secondary);
  font-size: 14px;
  max-width: 400px;
}

/* City List Styles */
.city-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.city-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px 20px;
  transition: all 0.3s ease;
}

.city-item:hover {
  border-color: var(--border-hover);
  box-shadow: var(--shadow-hover);
}

.city-info {
  flex: 1;
}

.city-main {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.city-name-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.city-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.city-code {
  font-size: 14px;
  color: var(--text-muted);
}

.city-meta {
  display: flex;
  gap: 16px;
}

.meta-item {
  font-size: 14px;
  color: var(--text-secondary);
}

/* Operations Styles */
.city-operations {
  display: flex;
  gap: 8px;
}

.op-btn {
  padding: 8px 16px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.update-btn {
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.update-btn:hover {
  background-color: var(--bg-tertiary);
  border-color: var(--border-hover);
}

.delete-btn {
  background-color: var(--bg-primary);
  color: var(--accent-danger);
  border-color: var(--accent-danger);
}

.delete-btn:hover {
  background-color: var(--accent-danger);
  color: var(--text-inverse);
}



/* City Footer */
.city-footer {
  background-color: var(--bg-secondary);
  border-top: 1px solid var(--border);
  margin-bottom: 20px;
  padding-bottom: 16px;
  flex-shrink: 0;
}

.footer-content {
  padding: 16px 20px;
  text-align: center;
}

.footer-text {
  margin: 0;
  font-size: 14px;
  color: var(--text-muted);
  font-weight: 400;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: var(--bg-card);
  border-radius: 12px;
  border: 1px solid var(--border);
  box-shadow: var(--shadow-hover);
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border);
  background: var(--bg-primary);
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-muted);
  font-size: 24px;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

/* Form Styles */
.city-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.form-input, .form-textarea {
  padding: 12px 16px;
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 8px;
  color: var(--text-primary);
  font-size: 14px;
  transition: all 0.3s ease;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.1);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid var(--border);
  margin-top: 20px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 100px;
  justify-content: center;
}

.btn-secondary {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.btn-secondary:hover {
  background: var(--bg-card);
}

.btn-primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.btn-primary:hover:not(:disabled) {
  background: var(--accent-primary-hover);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Responsive Design */
@media (max-width: 1024px) {
  .city-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .city-operations {
    justify-content: flex-end;
  }
}

@media (max-width: 768px) {
  .city-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: flex-end;
  }
  
  .city-content {
    padding: 16px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .modal-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
  
  .pagination-controls {
    flex-wrap: wrap;
  }
}

/* Scrollbar Styles */
.city-content::-webkit-scrollbar {
  width: 8px;
}

.city-content::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 4px;
}

.city-content::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 4px;
}

.city-content::-webkit-scrollbar-thumb:hover {
  background: var(--border-hover);
}
</style>